package sjtu.ist.warehouse4ws.dynamicDS;

import java.util.Map;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.apache.struts2.ServletActionContext;
import org.hibernate.EmptyInterceptor;

import sjtu.ist.warehouse4ws.model.ShiroUser;

import com.opensymphony.xwork2.ActionContext;

public class CustInterceptor extends EmptyInterceptor {
	private static ThreadLocal local = new ThreadLocal();
	
	public CustInterceptor(){
	}
	
	public static void setPrefix(String prefix){
		local.set(prefix+"_");
	}
	
	public String onPrepareStatement(String sql) {  

		ActionContext ac=ActionContext.getContext();
		Map<String,Object> session=ac.getSession();
		
		String sessionId=ServletActionContext.getRequest().getSession().getId();
		System.out.println("interceptor:"+sessionId);
		
		Subject currentUser = SecurityUtils.getSubject();		
		Integer company=(Integer) session.get("companyId");
	
		if(!currentUser.isAuthenticated()){
			Integer cid=(Integer)session.get("companyId");
			if(cid==null ){
				return sql;
			}
			if(cid==0){
				return sql;
			}else{
				company=cid;
			}
		}else{
			Object role=currentUser.getSession().getAttribute("role");
			
			if(role==null || role.toString().equals("superadmin")){
				return sql;
			}
		}
		
		String prefix=company+"_";
		System.out.println(company);
		
        //根据用户的时间替换sql中的表名  
		System.out.println("original:"+sql);
		String newsql=sql;
		int start=newsql.indexOf("cust_");		
		while(start>0  && (newsql.charAt(start-1)==' ' || newsql.charAt(start-1)=='.')){

			newsql=newsql.substring(0, start)+prefix+newsql.substring(start);
			start+=prefix.length()+5;
			start=newsql.indexOf("cust_",start);
		}
		System.out.println("modified:"+newsql);
        return newsql; 
	
    }  

}
